package com.ljl.mvvmdemo.ui.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.ljl.mvvmdemo.BR
import com.ljl.mvvmdemo.R
import com.ljl.mvvmdemo.viewmodel.BaseViewModel
import java.lang.reflect.ParameterizedType

/**
 * Dialog 基类
 * created by luojialun on 2024/5/27
 */
abstract class BaseDialog<DB : ViewDataBinding, VM : BaseViewModel> : DialogFragment() {

    lateinit var binding: DB
    lateinit var viewModel: VM

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = this
        viewModel = ViewModelProvider(this).get(getViewModelClass())
        binding.setVariable(BR.viewModel, viewModel)
        lifecycle.addObserver(viewModel)

        setStyle(STYLE_NO_FRAME, setDialogStyle())

        val window = dialog?.window
        window?.let {
            it.setBackgroundDrawableResource(android.R.color.transparent)
            val params = it.attributes
            params.width = width()
            params.height = height()
            it.attributes = params
        }

        initParam()
        initView()
    }

    /**
     * 宽度
     *  @return WindowManager.LayoutParams.WRAP_CONTENT   WindowManager.LayoutParams.MATCH_PARENT
     */
    private fun width(): Int {
        return WindowManager.LayoutParams.WRAP_CONTENT
    }

    /**
     * 高度
     * @return WindowManager.LayoutParams.WRAP_CONTENT   WindowManager.LayoutParams.MATCH_PARENT
     */
    private fun height(): Int {
        return WindowManager.LayoutParams.WRAP_CONTENT
    }

    protected open fun setDialogStyle(): Int {
        return R.style.DialogStyle //  R.style.DialogStyle_transparent
    }

    open fun getViewModelClass(): Class<VM> {
        return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VM>
    }

    abstract fun getLayoutId(): Int

    open fun initParam() {}

    abstract fun initView()

    override fun onDestroyView() {
        super.onDestroyView()
        binding.unbind()
    }

}